<?php


namespace app\controller\api;


use app\BaseController;
use app\models\coupon\CouponModel;
use app\models\user\UserCouponModel;
use app\models\user\UserModel;

use app\services\config\ConfigService;
use think\App;
use think\facade\Db;
use think\facade\Log;
use zjkal\TimeHelper;

class WxController extends BaseController
{
    protected $appId;
    protected $appSecret;

    protected $scopeUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';

    public function __construct(App $app)
    {
        parent::__construct($app);
        $config = ConfigService::getConfigValueArray(['wechat_app_id', 'wechat_app_secret']);
        $this->appId = $config['wechat_app_id'];
        $this->appSecret = $config['wechat_app_secret'];
    }

    /**
     * 微信授权登陆
     * @return \think\response\Json
     */
    public function getAccessToken()
    {
        Db::startTrans();
        try {
            $code = $this->request->param('code', '', 'trim');
            if (!$code) {
                throw new \Exception("code不能为空");
            }
            $scopeUrl = sprintf($this->scopeUrl, $this->appId, $this->appSecret, $code);
            $res = curl_get($scopeUrl);
            $accessInfo = json_decode($res, true);
            if (isset($accessInfo['errcode'])) {
                throw new \Exception($accessInfo['errmsg'].' -  code:'.$accessInfo['errcode']);
            }
            $openId = $accessInfo['openid'];
//            $wxUserInfo = $this->getUserInfo($accessInfo['access_token'], $openId);
//            $wxUserInfoArr = json_decode($wxUserInfo, true);
            $existsUser = UserModel::where('open_id', $openId)->find();
            if ($existsUser) {
                $existsUser->token = $accessInfo['session_key'];
                $existsUser->valid_time = 604800 + time();
                $existsUser->save();
                Db::commit();
                return $this->success(['token' => $accessInfo['session_key']]);
            }
            $inviteCode = $this->request->param('invite_code', '');
            if ($inviteCode) {
                $inviteUserInfo = UserModel::where('invite_code', $inviteCode)->find();
                $pid = $inviteUserInfo['id'] ?? 0;
            } else {
                $pid = 0;
            }
            $model = new  UserModel();
            $model->nick = '默认昵称';
            $model->invite_code = strtoupper(createUserCode());
            $model->avatar = '';
            $model->inviter = $pid;
            $model->token = $accessInfo['session_key'];
            $model->valid_time = 604800 + time();
            $model->open_id = $openId;
            $model->save();
            $id = $model->id;
            $user = UserModel::find($id);
            if ($pid == 0) {
                $referrer = $id . '-';
            } else {
                $inviteUserInfo->promote_count = $inviteUserInfo['promote_count'] + 1;
                $inviteUserInfo->save();
                $referrer = $inviteUserInfo['referrer'] . $id . '-';
            }
            $user->referrer = $referrer;
            $user->save();
            $newcomer_coupons = ConfigService::getConfigValue('newcomer_coupons');
            if($newcomer_coupons){
                CouponModel::where(['type' => 0,'status' => 0])->select()->each(function ($item) use($id){
                    if($item['time_type']){
                        $start_time = time();
                        $end_time = strtotime('+'.$item['use_day'].' day',$start_time);
                    }else{
                        $start_time = $item['use_start_time'];
                        $end_time = $item['use_end_time'];
                    }
                    UserCouponModel::create([
                        'user_id' => $id,
                        'coupon_id' => $item['id'],
                        'is_used' => 0,
                        'coupon_name' => $item['coupon_name'],
                        'coupon_type' => $item['coupon_type'],
                        'amount' => $item['amount'],
                        'less_amount' => 0,
                        'use_start_time' => $start_time,
                        'use_end_time' => $end_time,
                        'use_type' => $item['use_type'],
                        'type_id' => json_encode($item['type_id']),
                        'create_time' => time(),
                    ]);

                });
            }
            Db::commit();
            return $this->success(['token' => $accessInfo['session_key']]);
        } catch (\Exception $exception) {
            Db::rollback();
            file_put_contents(date('m-d') . 'wx_scope_err.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
            return $this->error($exception->getMessage(), [], $exception->getCode());
        }
    }

    public function getUserInfo($accessToken, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openid&lang=zh_CN";
        $userInfo = curl_get($url);
        return $userInfo;
    }

    public function sendTemplateMsg($openId, $templateId, $page, $data)
    {
        $token = $this->getToken();
        // 推送数据 数组
        $data = [
            "touser" => $openId,        //接收者的openid
            "template_id" => $templateId, //申请的消息模板id
            "url" => $page, //推送消息中点击跳转的链接，不填就不会跳转
            "data" => $data
        ];
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=$token";
        $result = curl_post($url, json_encode($data, JSON_UNESCAPED_UNICODE));
        var_dump($result);
    }

    public function getToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
        $res = curl_get($url);
        $result = json_decode($res, true);
        return $result['access_token'];
    }

    public function test()
    {
        try {
            $tid = "p6cjEpO5_hJKN9meyR3tRqk-x6CQJOff0t54HrssdZc";
            $page = 'https://h5.xiangmiyan.com/#/pages/userlist/contacts/contacts';
            $date = date('Y年m月d日 H:i');
            $data = [
                'amount1' => ['value' => 100],
                'thing2' => ['value' => 'test'],
                'thing7' => ['value' => 'zhangsan']
            ];
            $this->sendTemplateMsg('ov2Lr6ZpEd5gEOYrn-jTD_GbxgPA', $tid, $page, $data);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function check()
    {
        echo $this->request->param('echostr');
        die;
        return $this->success();
    }
}